import router from './router/index.js'
import store from './store'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { isHttp } from '@/utils/validate'
import getters from './store/getter'
import path from 'path/posix'

// 路由守卫
NProgress.configure({ showSpinner: false });

const whiteList = ['/Login', '/auth-redirect', '/bind', '/register'];

router.beforeEach((to, from, next) => {
  NProgress.start()
  //有Token继续操作
  if (getToken()) {
    //如果有token再去登录页，自动跳到主页
    if (to.path === '/Login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (store.getters.roles.length === 0) {
        // 判断当前用户是否已拉取完user_info信息
        console.log("没有用户数据，重新拉取！");
        store.dispatch('GetInfo').then(() => {
          store.dispatch('GenerateRoutes').then(accessRoutes => {
            accessRoutes.forEach(route => {
              console.log(route);
              if (!isHttp(route.path)) {

                router.addRoute(route)
              }
            })
            next({ ...to, replace: true })
          })
        }).catch(err => {
          store.dispatch('LogOut').then(() => {
            ElMessage.error("错误了这个！" + err)
            next({ path: '/' })
          })
        })
      } else {
        next()
      }
    }
  } else {
    //没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      ElMessage.info("请先登录")
      next({ path: '/Login' })
    }
  }

//   next()
})

router.afterEach(() => {
  NProgress.done()
})